package org.cocos2dx.lua;

import org.cocos2dx.bean.GameData;
import org.cocos2dx.lib.Cocos2dxLuaJavaBridge;

import android.util.Log;
import cn.bmob.v3.listener.UpdateListener;

import com.weibo.game.sdk.WeiboGameSDKAPI;
import com.weibo.game.sdk.callback.SinaGameCallBack;
import com.weibo.game.sdk.callback.SinaUser;

/**
 * 此类用来提供给lua端调用
 * 
 * 注：为了演示方便，本demo使用了第三方sdk BMob，主要用于云端保存游戏数据，便于测试账号登录数据同步
 * 新浪sdk自身不依赖BMob sdk，所以可以无视BMob相关的代码。
 * 
 * 接入方只需关注WeiboGameSDKAPI.xx()相关的api即可，例如：
 * WeiboGameSDKAPI.init()
 * WeiboGameSDKAPI.login()
 * WeiboGameSDKAPI.pay()
 * 
 * @author ye
 */
public class NativeMethod {
    private static final String TAG = "AppActivity";
    //新浪游戏sdk结果码
    private static final int SINA_SDK_START = 0;
    private static final int SINA_SDK_SUCCESS = 1;
    private static final int SINA_SDK_ERROR = 2;
    private static final int SINA_SDK_CANCEL = 3;
    
    //第三方sdk-BMob结果码
    private static final int BMOB_SDK_SUCESS = 1;
    //private static final int BMOB_SDK_ERROR = 2;
    
    /**判断是否已经登录*/
    public static boolean sdkIsLogin(){
    	return WeiboGameSDKAPI.isLogin(AppActivity.s_instance);
    }

    /**登录*/
    public static void sdkLogin(final int luaFunc) {
        WeiboGameSDKAPI.login(AppActivity.s_instance, new SinaGameCallBack() {
            @Override
            public void onResult(int code, final Object obj) {
                Log.d(TAG, "sdkLogin-onResult(): code = " + code + ", " + obj.toString());
                if (code == SINA_SDK_SUCCESS) {
                    // 成功
                    final SinaUser user = (SinaUser) obj;//调用obj.toString()能得到SinaUser对象的json数据
                    AppActivity.s_instance.setSinaUser(user);
                    //通知客户端SinaSdk登录成功，为了demo演示方便，只传递简单数据给lua，格式code|suid
                    String result = SINA_SDK_SUCCESS + "|" + user.getSuid();
                    Cocos2dxLuaJavaBridge.callLuaFunctionWithString(luaFunc, result);
                    Cocos2dxLuaJavaBridge.releaseLuaFunction(luaFunc);
                } else if (code == SINA_SDK_ERROR) {
                	//错误信息
                	Log.d(TAG, obj.toString());
                	Cocos2dxLuaJavaBridge.releaseLuaFunction(luaFunc);
                } else if (code == SINA_SDK_CANCEL) {
                    Log.d(TAG, "登录取消");
                    Cocos2dxLuaJavaBridge.releaseLuaFunction(luaFunc);
                }
            }

        });
    }

	/**
	 * 支付
	 * @param amount  支付金额（单位分）
	 * @param subject 支付标题
	 * @param desc 支付描述
	 */
    public static void sdkPay(final int amount, final String subject, final String desc, final int luaFunc) {
        if(!WeiboGameSDKAPI.isLogin(AppActivity.s_instance)){
        	AppActivity.s_instance.toastShort("支付前，请先登入");
            return;
        }
        
        WeiboGameSDKAPI.pay(AppActivity.s_instance, amount, subject, desc, new SinaGameCallBack() {
            @Override
            public void onResult(final int code, final Object obj) {
                // 该方法会回调多次，第一次code==start，第二次为成功、失败或取消
            	Log.d(TAG, "sdkPay-onResult(): code = " + code + ", " + obj.toString());
                if (code == SINA_SDK_SUCCESS) {
                	AppActivity.s_instance.toastShort("支付成功，订单号： " + obj.toString());
                }

                AppActivity.s_instance.runOnGLThread(new Runnable() {
                    @Override
                    public void run() {
                        // 此处为了演示方便，直接将userName传给lua了，实际游戏里可以将json数据传给lua
                        Cocos2dxLuaJavaBridge.callLuaFunctionWithString(luaFunc, String.valueOf(code));

                        if (code != SINA_SDK_START) {
                            // 注意！！，此处只有当code不是start时，才进行release操作，不然第二次调用时，luaFunc已被回收，上面的回调失败
                            Cocos2dxLuaJavaBridge.releaseLuaFunction(luaFunc);
                        }
                    }
                });
            }
        });
    }

    /**退出*/
    public static void sdkExit(final int luaFunc) {
        WeiboGameSDKAPI.exit(AppActivity.s_instance, new SinaGameCallBack() {
            @Override
            public void onResult(final int code, Object obj) {
            	Log.d(TAG, "sdkExit-onResult(): code = " + code + ", " + obj.toString());
                AppActivity.s_instance.runOnGLThread(new Runnable() {
                    @Override
                    public void run() {
                        // 可以直接在这里结束游戏，或者将code作为参数传给lua，通知lua结束游戏
                        Cocos2dxLuaJavaBridge.callLuaFunctionWithString(luaFunc, String.valueOf(code));
                        Cocos2dxLuaJavaBridge.releaseLuaFunction(luaFunc);
                    }
                });
            }
        });
    }
    
    /**注销*/
    public static void sdkLogout() {
    	Log.d(TAG, "sdkLogout-onResult()");
    	WeiboGameSDKAPI.logout(AppActivity.s_instance);
    	AppActivity.s_instance.toastShort("注销成功");
    }
    
    /**此方法使用了第三方sdk存储游戏数据，只是用作游戏数据同步演示，请无视*/
    public static void jniRequestGameData(String suid, final int luaFunc) {
    	Log.d(TAG, "jniRequestGameData(), suid = " + suid);
        //判断游戏服务器BMob是否已记录用户信息
        AppActivity.s_instance.requestBmodGameUser(suid, luaFunc);
    }
    
    /**此方法使用了第三方sdk存储游戏数据，只是用作游戏数据同步演示，请无视*/
    public static void jniSubmitScore(int highScore, final int luaFunc) {
    	Log.d(TAG, "jniSubmitScore(): " + highScore);
    	GameData data = AppActivity.s_instance.getGameData();
    	if (data.getHighScore() >= highScore) {
    		//低分数不提交，也算请求成功
    		Log.d(TAG, "当前分数比服务器上的低，不提交");
    		Cocos2dxLuaJavaBridge.callLuaFunctionWithString(luaFunc, String.valueOf(BMOB_SDK_SUCESS));
    		Cocos2dxLuaJavaBridge.releaseLuaFunction(luaFunc);
    		return;
    	}
    	
    	AppActivity.s_instance.showProgressDialog(true);
    	submitScore(highScore, luaFunc, false);
    }
    
    /**此方法使用了第三方sdk存储游戏数据，只是用作游戏数据同步演示，请无视*/
    public static void submitScore(final int highScore, final int luaFunc, final boolean isRetry) {
    	Log.d(TAG, "submitScore(): " + highScore);
    	GameData data = AppActivity.s_instance.getGameData();
    	data.setHighScore(highScore);
    	data.update(AppActivity.s_instance, new UpdateListener() {
    		@Override
    		public void onStart() {
    			if (isRetry) {
    				try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
    			}
    			super.onStart();
    		}
    		
			@Override
			public void onSuccess() {
				Log.d(TAG, "submitScore-onSuccess()");
				AppActivity.s_instance.showProgressDialog(false);
                // 可以直接在这里结束游戏，或者将code作为参数传给lua，通知lua结束游戏
                Cocos2dxLuaJavaBridge.callLuaFunctionWithString(luaFunc, String.valueOf(BMOB_SDK_SUCESS));
                Cocos2dxLuaJavaBridge.releaseLuaFunction(luaFunc);
			}
			
			@Override
			public void onFailure(int code, String error) {
				//失败则无限重试
				Log.d(TAG, "submitScore-onFailure(), 重试！");
				submitScore(highScore, luaFunc, true);
			}
		});
    }
    
    /**此方法使用了第三方sdk存储游戏数据，只是用作游戏数据同步演示，请无视*/
    public static void jniAddGold(int gold, final int luaFunc) {
    	Log.d(TAG, "jniAddGold(): " + gold);
    	AppActivity.s_instance.showProgressDialog(true);
    	addGold(gold, luaFunc, false);
    }
    
    /**此方法使用了第三方sdk存储游戏数据，只是用作游戏数据同步演示，请无视*/
    public static void addGold(final int gold, final int luaFunc, final boolean isRetry) {
    	Log.d(TAG, "addGold(): " + gold);
    	GameData data = AppActivity.s_instance.getGameData();
    	data.setGold(data.getGold() + gold);
    	data.update(AppActivity.s_instance, new UpdateListener() {
    		@Override
    		public void onStart() {
    			if (isRetry) {
    				try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
    			}
    			super.onStart();
    		}
    		
			@Override
			public void onSuccess() {
				Log.d(TAG, "addGold-onSuccess()");
				AppActivity.s_instance.showProgressDialog(false);
                Cocos2dxLuaJavaBridge.releaseLuaFunction(luaFunc);
			}
			
			@Override
			public void onFailure(int code, String error) {
				//失败则无限重试
				Log.d(TAG, "addGold-onFailure(), 重试！");
				addGold(gold, luaFunc, true);
			}
		});
    }
}
